package com.xjscrm.console.service.customer.groupSend.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.group.WwGroupQuery;
import com.xjscrm.console.param.groupSend.*;
import com.xjscrm.console.param.wwCustomer.CustomerQuery;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.groupSend.GroupSendService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import com.xjscrm.console.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GroupSendServiceImpl implements GroupSendService {

    @Autowired
    private GroupSendTaskMapper groupSendTaskMapper;

    @Autowired
    private GroupSendTaskCustomerMapper groupSendTaskCustomerMapper;

    @Autowired
    private GroupSendTaskDeviceMapper groupSendTaskDeviceMapper;
    
    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private WwDeviceService wwDeviceService;

    @Autowired
    private GroupSendTaskDeviceConfigMapper groupSendTaskDeviceConfigMapper;

    @Autowired
    private GroupSendJobMapper groupSendJobMapper;

    @Autowired
    private GroupSendJobMsgMapper groupSendJobMsgMapper;

    @Autowired
    private GroupSendJobDeviceMapper groupSendJobDeviceMapper;

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addGroupSendTask(GroupSendTaskDto groupSendTaskDto) {
        if(groupSendTaskDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupSendTaskDto.getGroupSendTaskDeviceDtoList()==null||groupSendTaskDto.getGroupSendTaskDeviceDtoList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        //保存群发任务
        GroupSendTask groupSendTask = new GroupSendTask();
        BeanUtil.copyProperties(groupSendTaskDto,groupSendTask);
        int time = DateUtil.getTime();
        long id = IdWorker.getId();
        groupSendTask.setId(id);
        groupSendTask.setCreateTime(time);
        groupSendTask.setUpdateTime(time);
        groupSendTaskMapper.insertGroupSendTask(groupSendTask);

        if(groupSendTaskDto.getGroupSendTaskCustomerDtoList()!=null&&!groupSendTaskDto.getGroupSendTaskCustomerDtoList().isEmpty()){
        //保存群发任务和客户关系
        for (GroupSendTaskCustomerDto groupSendTaskCustomerDto:groupSendTaskDto.getGroupSendTaskCustomerDtoList()) {
            GroupSendTaskCustomer groupSendTaskCustomer = new GroupSendTaskCustomer();
            BeanUtil.copyProperties(groupSendTaskCustomerDto,groupSendTaskCustomer);
            groupSendTaskCustomer.setTaskId(id);
            groupSendTaskCustomer.setMerId(groupSendTask.getMerId());
            groupSendTaskCustomerMapper.addGroupSendTaskCustomer(groupSendTaskCustomer);
        }
        }

        //保存群发任务和机器人关系
       for(GroupSendTaskDeviceDto groupSendTaskDeviceDto: groupSendTaskDto.getGroupSendTaskDeviceDtoList()){
           GroupSendTaskDevice groupSendTaskDevice=new GroupSendTaskDevice();
           BeanUtil.copyProperties(groupSendTaskDeviceDto,groupSendTaskDevice);
           groupSendTaskDevice.setTaskId(id);
           groupSendTaskDevice.setMerId(groupSendTask.getMerId());
           groupSendTaskDeviceMapper.addGroupSendTaskDevice(groupSendTaskDevice);
       }
    }

    @Override
    public Object getGroupSendTaskList(GroupSendTaskQuery groupSendTaskQuery) {
        if(groupSendTaskQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String orderBy = OrderByUtil.getOrderBy(groupSendTaskQuery.getOrderByField(), groupSendTaskQuery.isAsc());
        PageHelper.startPage(groupSendTaskQuery.getCurrent(),groupSendTaskQuery.getSize(),orderBy);
        List<GroupSendTaskVo> groupSendTaskVoList= groupSendTaskMapper.getGroupSendTaskList(groupSendTaskQuery);

        //获取机器人
        groupSendTaskVoList.forEach(it->{
            //获取关联的机器人ID
            GroupSendDeviceQuery groupSendDeviceQuery=new GroupSendDeviceQuery();
            groupSendDeviceQuery.setMerId(it.getMerId());
            groupSendDeviceQuery.setTaskId(it.getId());
            List<GroupSendDeviceVo> groupSendDeviceVoList= groupSendTaskDeviceMapper.getGroupSendTaskDeviceList(groupSendDeviceQuery);
            if(groupSendDeviceVoList!=null&&!groupSendDeviceVoList.isEmpty()){
                List<Long> deviceUniqueIds = groupSendDeviceVoList.stream().map(GroupSendDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
               //获取关联机器人的昵称
                WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
                wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
                wwDeviceQuery.setMerId(it.getMerId());
                List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                if(wwDeviceList!=null&&!wwDeviceList.isEmpty()){
                    List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                    it.setDeviceNames(deviceNames);
                }
            }
        });

        return new MyPageInfo<>(groupSendTaskVoList);
    }

    @Override
    public Object getGroupSendTaskDetail(GroupSendTaskDto groupSendTaskDto) {
        if(groupSendTaskDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupSendTaskDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupSendTask groupSendTask = groupSendTaskMapper.getById(groupSendTaskDto.getId(), groupSendTaskDto.getMerId());
        if(groupSendTask==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到改任务");
        }
        GroupSendTaskVo groupSendTaskVo = new GroupSendTaskVo();
        BeanUtil.copyProperties(groupSendTask,groupSendTaskVo);

        //获取关联的机器人ID
        GroupSendDeviceQuery groupSendDeviceQuery=new GroupSendDeviceQuery();
        groupSendDeviceQuery.setMerId(groupSendTask.getMerId());
        groupSendDeviceQuery.setTaskId(groupSendTask.getId());
        List<GroupSendDeviceVo> groupSendDeviceVoList= groupSendTaskDeviceMapper.getGroupSendTaskDeviceList(groupSendDeviceQuery);
        if(groupSendDeviceVoList!=null&&!groupSendDeviceVoList.isEmpty()){
            List<Long> deviceUniqueIds = groupSendDeviceVoList.stream().map(GroupSendDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
            //获取关联机器人的昵称
            WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
            wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
            wwDeviceQuery.setMerId(groupSendTask.getMerId());
            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if(wwDeviceList!=null&&!wwDeviceList.isEmpty()){
                groupSendTaskVo.setWwDeviceVoList(wwDeviceList);
                List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                groupSendTaskVo.setDeviceNames(deviceNames);
            }
        }

        //发给对象wxid（私聊就是客户wxid,群聊就是群wxid）
        List<String> sendWxids=new ArrayList<>();
        GroupSendTaskCustomerQuery groupSendTaskCustomerQuery=new GroupSendTaskCustomerQuery();
        groupSendTaskCustomerQuery.setMerId(groupSendTask.getMerId());
        groupSendTaskCustomerQuery.setTaskId(groupSendTask.getId());
        List<GroupSendTaskCustomerVo> groupSendTaskCustomerList = groupSendTaskCustomerMapper.getGroupSendTaskCustomerList(groupSendTaskCustomerQuery);
        if(groupSendTaskCustomerList!=null&&!groupSendTaskCustomerList.isEmpty()){
          sendWxids = groupSendTaskCustomerList.stream().map(GroupSendTaskCustomerVo::getSendWxid).distinct().collect(Collectors.toList());
        }
        //获取客户
        if(sendWxids!=null&&!sendWxids.isEmpty()&&groupSendTask.getCustomerType()!=null&&groupSendTask.getCustomerType().equals(2)){
            CustomerQuery customerQuery=new CustomerQuery();
            customerQuery.setMerId(groupSendTask.getMerId());
            customerQuery.setWxids(sendWxids);
            List<WwCustomerVo> wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
            if(wwCustomerVoList!=null&&!wwCustomerVoList.isEmpty()){
                wwCustomerVoList.forEach(it->{
                    WwDevice wwDevice = wwDeviceMapper.getById(it.getDeviceUniqueId(), it.getMerId());
                    if(wwDevice!=null){
                        it.setDeviceName(wwDevice.getDeviceName());
                        it.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }
                });
                groupSendTaskVo.setWwCustomerVoList(wwCustomerVoList);
            }

        }
       //获取客户群
        if(sendWxids!=null&&!sendWxids.isEmpty()&&groupSendTask.getGroupType()!=null&&groupSendTask.getGroupType().equals(2)){
            WwGroupQuery wwGroupQuery=new WwGroupQuery();
            wwGroupQuery.setMerId(groupSendTask.getMerId());
            wwGroupQuery.setGroupWxids(sendWxids);
            List<WwGroupVo> wwGroupList = wwGroupMapper.getWwGroupList(wwGroupQuery);
            if(wwGroupList!=null&&!wwGroupList.isEmpty()){
                wwGroupList.forEach(it->{
                    WwDevice wwDevice = wwDeviceMapper.getById(it.getDeviceUniqueId(), it.getMerId());
                    if(wwDevice!=null){
                        it.setDeviceName(wwDevice.getDeviceName());
                        it.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }
                });
                groupSendTaskVo.setWwGroupVoList(wwGroupList);
            }
        }
        return groupSendTaskVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroupSendTask(GroupSendTaskDto groupSendTaskDto) {
        if(groupSendTaskDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if(groupSendTaskDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupSendTaskDto.getGroupSendTaskDeviceDtoList()==null||groupSendTaskDto.getGroupSendTaskDeviceDtoList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(groupSendTaskDto.getType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "立即发送类型不支持编辑");
        }

        GroupSendTask groupSendTask=groupSendTaskMapper.getById(groupSendTaskDto.getId(),groupSendTaskDto.getMerId());
        if(groupSendTask==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }

        //修改群发任务
        BeanUtil.copyProperties(groupSendTaskDto,groupSendTask);
        groupSendTaskMapper.update(groupSendTask);


        //查询群发任务和客户/群关系 删除旧数据
        GroupSendTaskCustomerQuery groupSendTaskCustomerQuery=new GroupSendTaskCustomerQuery();
        groupSendTaskCustomerQuery.setMerId(groupSendTask.getMerId());
        groupSendTaskCustomerQuery.setTaskId(groupSendTask.getId());
        List<GroupSendTaskCustomerVo> groupSendTaskCustomerVoList=groupSendTaskCustomerMapper.getGroupSendTaskCustomerList(groupSendTaskCustomerQuery);
        if(groupSendTaskCustomerVoList!=null&&!groupSendTaskCustomerVoList.isEmpty()){
            groupSendTaskCustomerVoList.forEach(it->groupSendTaskCustomerMapper.deleById(it.getId(),it.getMerId()));
        }

        if(groupSendTaskDto.getGroupSendTaskCustomerDtoList()!=null&&!groupSendTaskDto.getGroupSendTaskCustomerDtoList().isEmpty()) {
            //保存群发任务和客户关系
            for (GroupSendTaskCustomerDto groupSendTaskCustomerDto : groupSendTaskDto.getGroupSendTaskCustomerDtoList()) {
                GroupSendTaskCustomer groupSendTaskCustomer = new GroupSendTaskCustomer();
                BeanUtil.copyProperties(groupSendTaskCustomerDto, groupSendTaskCustomer);
                groupSendTaskCustomer.setTaskId(groupSendTask.getId());
                groupSendTaskCustomer.setMerId(groupSendTask.getMerId());
                groupSendTaskCustomerMapper.addGroupSendTaskCustomer(groupSendTaskCustomer);
            }
        }

        //查询群发任务和机器人关系 删除旧数据
        GroupSendDeviceQuery groupSendDeviceQuery=new GroupSendDeviceQuery();
        groupSendDeviceQuery.setMerId(groupSendTask.getMerId());
        groupSendDeviceQuery.setTaskId(groupSendTask.getId());
        List<GroupSendDeviceVo> groupSendTaskDeviceList = groupSendTaskDeviceMapper.getGroupSendTaskDeviceList(groupSendDeviceQuery);
        if(groupSendTaskDeviceList!=null&&!groupSendTaskDeviceList.isEmpty()){
            groupSendTaskDeviceList.forEach(it->groupSendTaskDeviceMapper.deleById(it.getId(),it.getMerId()));
        }

        //保存群发任务和机器人关系
        for(GroupSendTaskDeviceDto groupSendTaskDeviceDto: groupSendTaskDto.getGroupSendTaskDeviceDtoList()){
            GroupSendTaskDevice groupSendTaskDevice=new GroupSendTaskDevice();
            BeanUtil.copyProperties(groupSendTaskDeviceDto,groupSendTaskDevice);
            groupSendTaskDevice.setTaskId(groupSendTask.getId());
            groupSendTaskDevice.setMerId(groupSendTask.getMerId());
            groupSendTaskDeviceMapper.addGroupSendTaskDevice(groupSendTaskDevice);
        }

    }

    @Override
    public void startAndStop(StartAndStopDto startAndStopDto) {
        if(startAndStopDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if(startAndStopDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        GroupSendTask groupSendTask=groupSendTaskMapper.getById(startAndStopDto.getId(),startAndStopDto.getMerId());

        if(groupSendTask==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }

        groupSendTask.setStatus(startAndStopDto.getStatus());
        groupSendTaskMapper.update(groupSendTask);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleGroupSendTask(GroupSendTaskDto groupSendTaskDto) {
        if(groupSendTaskDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if(groupSendTaskDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        GroupSendTask groupSendTask=groupSendTaskMapper.getById(groupSendTaskDto.getId(),groupSendTaskDto.getMerId());

        if(groupSendTask==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }

        //查询群发任务和客户/群关系 删除旧数据
        GroupSendTaskCustomerQuery groupSendTaskCustomerQuery=new GroupSendTaskCustomerQuery();
        groupSendTaskCustomerQuery.setMerId(groupSendTask.getMerId());
        groupSendTaskCustomerQuery.setTaskId(groupSendTask.getId());
        List<GroupSendTaskCustomerVo> groupSendTaskCustomerVoList=groupSendTaskCustomerMapper.getGroupSendTaskCustomerList(groupSendTaskCustomerQuery);
        if(groupSendTaskCustomerVoList!=null&&!groupSendTaskCustomerVoList.isEmpty()){
            groupSendTaskCustomerVoList.forEach(it->groupSendTaskCustomerMapper.deleById(it.getId(),it.getMerId()));
        }

        //查询群发任务和机器人关系 删除旧数据
        GroupSendDeviceQuery groupSendDeviceQuery=new GroupSendDeviceQuery();
        groupSendDeviceQuery.setMerId(groupSendTask.getMerId());
        groupSendDeviceQuery.setTaskId(groupSendTask.getId());
        List<GroupSendDeviceVo> groupSendTaskDeviceList = groupSendTaskDeviceMapper.getGroupSendTaskDeviceList(groupSendDeviceQuery);
        if(groupSendTaskDeviceList!=null&&!groupSendTaskDeviceList.isEmpty()){
            groupSendTaskDeviceList.forEach(it->groupSendTaskDeviceMapper.deleById(it.getId(),it.getMerId()));
        }

        //删除群发任务
        groupSendTaskMapper.deleById(groupSendTask.getId(),groupSendTask.getMerId());
    }

    @Override
    public Object getDeviceList(WwDeviceQuery wwDeviceQuery) {
        if(wwDeviceQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        List<GroupSendTaskDeviceConfigVo> groupSendTaskDeviceConfigVoList=new ArrayList<>();

        MyPageInfo<WwDeviceVo> wwDeviceVoMyPageInfo = wwDeviceService.getWwDevice(wwDeviceQuery);
        if(wwDeviceVoMyPageInfo.getRecords()!=null&&!wwDeviceVoMyPageInfo.getRecords().isEmpty()){
            for (WwDeviceVo wwDeviceVo:wwDeviceVoMyPageInfo.getRecords()) {
                try {
                    GroupSendTaskDeviceConfigVo groupSendTaskDeviceConfigVo = new GroupSendTaskDeviceConfigVo();
                    groupSendTaskDeviceConfigVo.setDeviceUniqueId(wwDeviceVo.getId());
                    groupSendTaskDeviceConfigVo.setDeviceName(wwDeviceVo.getDeviceName());
                    groupSendTaskDeviceConfigVo.setDeviceHeaderImage(wwDeviceVo.getHeadImgUrl());
                    groupSendTaskDeviceConfigVo.setMerId(wwDeviceVo.getMerId());

                    GroupSendTaskDeviceConfig groupSendTaskDeviceConfig=groupSendTaskDeviceConfigMapper.getByDeviceUniqueId(wwDeviceVo.getId(),wwDeviceVo.getMerId());
                    if(groupSendTaskDeviceConfig!=null){
                        groupSendTaskDeviceConfigVo.setId(groupSendTaskDeviceConfig.getId());
                        groupSendTaskDeviceConfigVo.setRateMin(groupSendTaskDeviceConfig.getRateMin());
                        groupSendTaskDeviceConfigVo.setRateMax(groupSendTaskDeviceConfig.getRateMax());
                        groupSendTaskDeviceConfigVo.setSleepRule(JSONObject.parseObject(groupSendTaskDeviceConfig.getRule(), OperatorPlanDeviceRule.class));
                    }
                    groupSendTaskDeviceConfigVoList.add(groupSendTaskDeviceConfigVo);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        MyPageInfo<GroupSendTaskDeviceConfigVo> groupSendTaskDeviceConfigVoMyPageInfo = new MyPageInfo<>(groupSendTaskDeviceConfigVoList);
        groupSendTaskDeviceConfigVoMyPageInfo.setPages(wwDeviceVoMyPageInfo.getPages());
        groupSendTaskDeviceConfigVoMyPageInfo.setTotal(wwDeviceVoMyPageInfo.getTotal());
        groupSendTaskDeviceConfigVoMyPageInfo.setSize(wwDeviceVoMyPageInfo.getSize());
        groupSendTaskDeviceConfigVoMyPageInfo.setCurrent(wwDeviceVoMyPageInfo.getCurrent());
        return groupSendTaskDeviceConfigVoMyPageInfo;
    }

    @Override
    public void updatesleeprule(UpdateSleepRuleDto updateSleepRuleDto) {
        if(updateSleepRuleDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(updateSleepRuleDto.getDeviceUniqueId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        if(updateSleepRuleDto.getId()==null){
            //新建
            GroupSendTaskDeviceConfig groupSendTaskDeviceConfig=new GroupSendTaskDeviceConfig();
            BeanUtil.copyProperties(updateSleepRuleDto,groupSendTaskDeviceConfig);
            groupSendTaskDeviceConfig.setRule(JSONObject.toJSONString(updateSleepRuleDto.getSleepRule()));
            groupSendTaskDeviceConfigMapper.addGroupSendTaskDeviceConfig(groupSendTaskDeviceConfig);
        }
        if(updateSleepRuleDto.getId()!=null){
            //修改
          GroupSendTaskDeviceConfig groupSendTaskDeviceConfig=  groupSendTaskDeviceConfigMapper.getById(updateSleepRuleDto.getId(),updateSleepRuleDto.getMerId());

          if(groupSendTaskDeviceConfig!=null){
              BeanUtil.copyProperties(updateSleepRuleDto,groupSendTaskDeviceConfig);
              groupSendTaskDeviceConfig.setRule(JSONObject.toJSONString(updateSleepRuleDto.getSleepRule()));
              groupSendTaskDeviceConfigMapper.update(groupSendTaskDeviceConfig);
          }
        }
    }

    @Override
    public Object getGroupSendJobList(GroupSendJobQuery groupSendJobquery) {
        if(groupSendJobquery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String orderBy = OrderByUtil.getOrderBy(groupSendJobquery.getOrderByField(), groupSendJobquery.isAsc());
        PageHelper.startPage(groupSendJobquery.getCurrent(), groupSendJobquery.getSize(), orderBy);
        List<GroupSendJobVo> groupSendJobVoList= groupSendJobMapper.getGroupSendJobList(groupSendJobquery);
        if(groupSendJobVoList!=null&&!groupSendJobVoList.isEmpty()){
            //获取机器人
            groupSendJobVoList.forEach(it->{
                //获取关联的机器人ID
                GroupSendJobDeviceQuery groupSendJobDeviceQuery=new GroupSendJobDeviceQuery();
                groupSendJobDeviceQuery.setMerId(it.getMerId());
                groupSendJobDeviceQuery.setJobId(it.getId());
                List<GroupSendJobDeviceVo> groupSendJobDeviceVoList = groupSendJobDeviceMapper.getGroupSendJobDeviceList(groupSendJobDeviceQuery);

                if(groupSendJobDeviceVoList!=null&&!groupSendJobDeviceVoList.isEmpty()){
                    List<Long> deviceUniqueIds = groupSendJobDeviceVoList.stream().map(GroupSendJobDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
                    //获取关联机器人的昵称
                    WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
                    wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
                    wwDeviceQuery.setMerId(it.getMerId());
                    List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                    if(wwDeviceList!=null&&!wwDeviceList.isEmpty()){
                        List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                        it.setDeviceNames(deviceNames);
                    }
                }
            });
        }
        return new MyPageInfo<>(groupSendJobVoList);
    }


    @Override
    public Object getGroupSendJobMsgList(GroupSendJobMsgQuery groupSendJobMsgQuery) {
        if(groupSendJobMsgQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupSendJobMsgQuery.getJobId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        GroupSendJob groupSendJob=groupSendJobMapper.getById(groupSendJobMsgQuery.getJobId(),groupSendJobMsgQuery.getMerId());
        if(groupSendJob==null||groupSendJob.getStartSendTime()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "任务不存在或开始发送时间为空");
        }

        groupSendJobMsgQuery.setStartSendTime(groupSendJob.getStartSendTime());
        String orderBy = OrderByUtil.getOrderBy(groupSendJobMsgQuery.getOrderByField(), groupSendJobMsgQuery.isAsc());
        PageHelper.startPage(groupSendJobMsgQuery.getCurrent(), groupSendJobMsgQuery.getSize(), orderBy);
       List<GroupSendJobMsgVo> groupSendJobMsgVoList=groupSendJobMsgMapper.getGroupSendJobMsgList(groupSendJobMsgQuery);
       if(groupSendJobMsgVoList!=null&&!groupSendJobMsgVoList.isEmpty()){
           groupSendJobMsgVoList.forEach(it->{
               it.setSendTime(groupSendJobMsgQuery.getStartSendTime()+it.getDelay());

               //获取客户头像和客户昵称
               if(it.getType()!=null&&it.getType()==0){
                   WwCustomer wwCustomer = wwCustomerMapper.getByWxId(it.getSendWxid(), it.getMerId());
                   if(wwCustomer!=null){
                       it.setSendWxName(wwCustomer.getName());
                       it.setHeadImageUrl(wwCustomer.getHeadImgUrl());
                   }
               }

               //获取群头像和群名
               if(it.getType()!=null&&it.getType()==1){
                   WwGroup wwGroup = wwGroupMapper.selectByGroupWxId(it.getMerId(), it.getDeviceUniqueId(), it.getSendWxid());
                   if(wwGroup!=null){
                       it.setSendWxName(wwGroup.getGroupName());
                       it.setHeadImageUrl(wwGroup.getHeadImageUrl());
                   }
               }
           });

       }

        return new MyPageInfo<>(groupSendJobMsgVoList);
    }


    @Override
    public void breakGroupSendJob(BatchGroupSendJobDto batchGroupSendJobDto) {
        if(batchGroupSendJobDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchGroupSendJobDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupSendJob groupSendJob = groupSendJobMapper.getById(batchGroupSendJobDto.getId(), batchGroupSendJobDto.getMerId());
        if(groupSendJob==null||(groupSendJob.getStatus()!=null&&groupSendJob.getStatus().equals(3))){
            return;
        }
        groupSendJob.setStatus(3);
        groupSendJobMapper.update(groupSendJob);
    }

    @Override
    public void continueGroupSendJob(BatchGroupSendJobDto batchGroupSendJobDto) {
        if(batchGroupSendJobDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchGroupSendJobDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupSendJob groupSendJob = groupSendJobMapper.getById(batchGroupSendJobDto.getId(), batchGroupSendJobDto.getMerId());
        if(groupSendJob==null||(groupSendJob.getStatus()!=null&&groupSendJob.getStatus().equals(1))){
            return;
        }
        groupSendJob.setStatus(1);

        GroupSendJobDeviceQuery groupSendJobDeviceQuery=new GroupSendJobDeviceQuery();
        groupSendJobDeviceQuery.setMerId(groupSendJob.getMerId());
        groupSendJobDeviceQuery.setJobId(groupSendJob.getId());
        List<GroupSendJobDeviceVo> groupSendJobDeviceVoList=  groupSendJobDeviceMapper.getGroupSendJobDeviceList(groupSendJobDeviceQuery);
        if(groupSendJobDeviceVoList!=null&&!groupSendJobDeviceVoList.isEmpty()){
            for (GroupSendJobDeviceVo groupSendJobDeviceVo:groupSendJobDeviceVoList) {
                try {
                    //修改延迟时间
                    GroupSendJobMsgQuery groupSendJobMsgQuery=new GroupSendJobMsgQuery();
                    groupSendJobMsgQuery.setMerId(groupSendJobDeviceVo.getMerId());
                    groupSendJobMsgQuery.setJobId(groupSendJobDeviceVo.getJobId());
                    groupSendJobMsgQuery.setStatus(1);
                    groupSendJobMsgQuery.setDeviceUniqueId(groupSendJobDeviceVo.getDeviceUniqueId());
                    List<GroupSendJobMsgVo> groupSendJobMsgList = groupSendJobMsgMapper.getGroupSendJobMsgList(groupSendJobMsgQuery);
                    if(groupSendJobMsgList!=null&&!groupSendJobMsgList.isEmpty()){
                        for (GroupSendJobMsgVo groupSendJobMsgVo:groupSendJobMsgList) {
                            try {
                                GroupSendJobMsg groupSendJobMsg = new GroupSendJobMsg();
                                groupSendJobMsg.setId(groupSendJobMsgVo.getId());
                                groupSendJobMsg.setMerId(groupSendJobMsgVo.getMerId());
                                groupSendJobMsg.setDelay(Math.max((groupSendJobMsgVo.getDelay() - groupSendJobDeviceVo.getDelaySnapshot()), 0));
                                groupSendJobMsgMapper.update(groupSendJobMsg);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                    //延迟发送快照数清零
                    GroupSendJobDevice groupSendJobDevice=new GroupSendJobDevice();
                    groupSendJobDevice.setId(groupSendJobDeviceVo.getId());
                    groupSendJobDevice.setMerId(groupSendJobDeviceVo.getMerId());
                    groupSendJobDevice.setDelaySnapshot(0);
                    groupSendJobDeviceMapper.update(groupSendJobDevice);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        groupSendJobMapper.update(groupSendJob);
    }

    @Override
    public void cancelGroupSendJob(BatchGroupSendJobDto batchGroupSendJobDto) {
        if(batchGroupSendJobDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchGroupSendJobDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupSendJob groupSendJob = groupSendJobMapper.getById(batchGroupSendJobDto.getId(), batchGroupSendJobDto.getMerId());
        if(groupSendJob==null||(groupSendJob.getStatus()!=null&&groupSendJob.getStatus().equals(4))){
            return;
        }
        groupSendJob.setStatus(4);
        groupSendJobMapper.update(groupSendJob);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleGroupSendJob(BatchGroupSendJobDto batchGroupSendJobDto) {
        if(batchGroupSendJobDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchGroupSendJobDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupSendJob groupSendJob = groupSendJobMapper.getById(batchGroupSendJobDto.getId(), batchGroupSendJobDto.getMerId());
        if(groupSendJob==null){
            return;
        }

        GroupSendJobDeviceQuery groupSendJobDeviceQuery=new GroupSendJobDeviceQuery();
        groupSendJobDeviceQuery.setMerId(groupSendJob.getMerId());
        groupSendJobDeviceQuery.setJobId(groupSendJob.getId());
        List<GroupSendJobDeviceVo> groupSendJobDeviceList = groupSendJobDeviceMapper.getGroupSendJobDeviceList(groupSendJobDeviceQuery);
        if(groupSendJobDeviceList!=null&&!groupSendJobDeviceList.isEmpty()){
            groupSendJobDeviceList.forEach(it->groupSendJobDeviceMapper.deleById(it.getId(),it.getMerId()));
        }


        GroupSendJobMsgQuery groupSendJobMsgQuery=new GroupSendJobMsgQuery();
        groupSendJobMsgQuery.setMerId(groupSendJob.getMerId());
        groupSendJobMsgQuery.setJobId(groupSendJob.getId());
        List<GroupSendJobMsgVo> groupSendJobMsgList = groupSendJobMsgMapper.getGroupSendJobMsgList(groupSendJobMsgQuery);
        if(groupSendJobMsgList!=null&&!groupSendJobMsgList.isEmpty()){
            groupSendJobMsgList.forEach(it->groupSendJobMsgMapper.deleById(it.getId(),it.getMerId()));
        }


        groupSendJobMapper.deleById(groupSendJob.getId(),groupSendJob.getMerId());
    }
}
